// 销售单据页面
import React, {Component} from 'react';
import {DeviceEventEmitter, StatusBar, Text, View, TouchableWithoutFeedback, ScrollView, TouchableOpacity, StyleSheet, TextInput, FlatList} from 'react-native';

import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import storeActions from '../../../store/actions/store';
import {bindActionCreators} from 'redux';
import {is, fen_to_yuan} from '../../../utils';
import {Actions} from "react-native-router-flux";
import CheckBox from 'react-native-check-box'
import {connect} from "react-redux";
import Tips from "react-native-root-tips";
import {RNUSBPrinter} from "react-native-usb-printer-mi";
const Buffer = require('buffer').Buffer;
class orderPage extends Component {
    constructor(props){
        super(props);
        this.orderPage = 1;

        this.state = {
            isLoadMore:false,
            activeIndex:0,
            searchVal:'',
            order_no: '',
            useless: false,
            detailInfo: {
                order: ''
            },
            isPrint: false
        }
    }
    componentDidMount = async () => {
        const devices = await RNUSBPrinter.getUSBDeviceList();
        if (devices && devices.length) {
            let vendorId = '';
            let productId = '';
            let isPrint = false;
            let printedSelected = '';
            devices.forEach(item => {
                if (item.device_type == 7) {
                    vendorId = item.vendor_id;
                    productId = item.product_id;
                    isPrint = true;
                    this.setState({
                        isPrint: isPrint
                    })
                }
            });
            if (isPrint) {
                printedSelected = await RNUSBPrinter.connectPrinter(vendorId, productId);
            }
            this.setState(Object.assign({}, this.state, {
                printedSelected: printedSelected,
                devices: devices,
            }));
        }

        let {storeAction} = this.props;
        storeAction.getOrderList(1,this.props.user_id,this.props.order_no,(res) =>{
            if (res && res.status && res.data && res.data.length){
                if(this.props.order_no){
                    storeAction.getOrderDetail(this.props.order_no);
                    this.setState({
                        order_no: this.props.order_no
                    })
                } else {
                    let firstOrderNo = res.data[0].order_no;
                    this.setState({
                        order_no: firstOrderNo
                    });
                    storeAction.getOrderDetail(firstOrderNo, (res) => {
                        console.log(res);
                        if (res && res.status && res.data) {
                            console.log('获取到的数据', res.data);
                            this.setState({
                                detailInfo: res.data
                            })
                        }
                    });
                }
            }
        });
        //监听事件
        this.listener = DeviceEventEmitter.addListener('orderHasMore',(isLoadMore) => {
            this.setState({
                isLoadMore:isLoadMore
            })
        })
    }
    componentWillUnmount() {
        this.listener.remove();
    }

    // 打印单据
    printOrder() {
        if(this.state.printedSelected) {
            let {storeAction} = this.props;
            if (!this.state.order_no) {
                Tips.showFail('订单号错误');
                return
            }
            storeAction.getPrintInfo(this.state.order_no, res => {
                console.log('这个是打印接口', res);
                if (res.status) {
                    let arr = [];
                    Object.keys(res.data).forEach((v) => {
                        if (v !== 'logo' && v !== 'qrcode') {
                            res.data[v] = res.data[v].map((h) => {
                                return parseInt(h, 16)
                            })
                        }
                        arr.push(...res.data[v])
                    });
                    console.log('这个是之前的', arr);
                    var typedArray = new Buffer(arr);
                    console.log('获取到的', typedArray);
                    RNUSBPrinter.printTextCut(typedArray);
                }
            });
        }else{
            Tips.showFail('打印机未连接或者未授权');
        }
    }
    // 提交售后申请
    _submitAfterSale() {
        let {storeAction, storeState} = this.props;
        let data = {
            item_ids: [],
            order_no: this.state.order_no || storeState.orderList[0].order_no
        };
        let detailInfo = this.state.detailInfo;
        detailInfo.order.items.forEach(item => {
            if (item.isChecked && !item.is_refunded) {
                data.item_ids.push(item.id)
            }
        });
        if (data.item_ids.length == 0) {
            Tips.showFail('请选择需要售后的商品');
            return
        }
        storeAction.submitAfterSale(data, (res) => {
            if (res && res.status) {
                Actions.push('ApplyPages', {
                    order_no: this.state.order_no || storeState.orderList[0].order_no
                })
            }
        });
    }
    //创建空布局
    _createEmptyView(){
        return (
            <View style={{height:'100%', alignItems:'center', justifyContent:'center',paddingVertical: 20}}>
                <Text style={{fontSize:16}}>
                    暂无列表数据!!!
                </Text>
            </View>
        );
    }
    //加载更多
    _onLoadMore(){
        if(this.state.isLoadMore){
            this.orderPage = this.orderPage + 1;
            let {storeAction} = this.props;
            storeAction.getOrderList(this.orderPage,this.props.user_id,this.state.searchVal);
        }
    }
    //自己渲染订单列表数据
    _renderOrderList(rowDate,index){
        return(
            <TouchableWithoutFeedback onPress={() => this._clickOrderItem(index,rowDate.order_no)}>
                <View style={[style.orderItem,index == this.state.activeIndex ?  style.orderItemActive : '']}>
                    <View style={style.sItem}>
                        <Text style={[style.mText, index == this.state.activeIndex ? style.orderItemActiveText : '', {flex: 1}]}>订单号：{rowDate.order_no}</Text>
                        <Text style={[style.itemMoney, index == this.state.activeIndex ? style.orderItemActiveText : '']}>￥ {rowDate.total_yuan}</Text>
                    </View>
                    <View style={style.sItem}>
                        <Text style={[style.mText, index == this.state.activeIndex ? style.orderItemActiveText : '', {flex: 1}]}>会员号： {rowDate.user.mobile}</Text>
                        <Text style={[style.mText, index == this.state.activeIndex ? style.orderItemActiveText : '']}>{rowDate.submit_time}</Text>
                    </View>
                </View>
            </TouchableWithoutFeedback>
        )
    }
    //渲染商品列表
    _renderGoodsList(rowDate,index){
        console.log('这个是什么', rowDate);
        // return;
        return(
            <TouchableWithoutFeedback onPress={() => this.checkBoxChange(index)}>
                <View style={[style.detailInfoItem]}>
                    <View style={{flex: 3}}>
                        <Text>
                            {rowDate.item_name}；{rowDate.item_meta.specs_text}
                        </Text>
                    </View>
                    <View style={style.detailCenter}>
                        <Text>
                            {rowDate.quantity}
                        </Text>
                    </View>
                    <View style={style.detailCenter}>
                        <Text>
                            {fen_to_yuan(rowDate.unit_price)}
                        </Text>
                    </View>
                    <View style={style.detailCenter}>
                        <Text>
                            {fen_to_yuan(rowDate.total)}
                        </Text>
                    </View>
                    <View style={style.detailCenter}>
                        {/* <Text style={style.detailBtn}>
                        申请售后
                    </Text>*/}
                        {this._checkBoxRow(rowDate, index)}
                    </View>
                </View>
            </TouchableWithoutFeedback>
        )
    }

    // 是否申请过售后渲染
    _checkBoxRow(rowDate, index) {
        if(!rowDate.is_refunded) {
            return(
                <CheckBox
                    onClick={() => this.checkBoxChange(index)}
                    isChecked={rowDate.isChecked}
                    disabled={!rowDate.isChecked}
                >

                </CheckBox>
            )
        } else {
            return (
                <Text>已售后</Text>
            )
        }
    }
    //渲染订单详情数据
    _renderOrderDetail(){

        let{storeState} = this.props;
        if(storeState.orderList.length){
            if (this.state.detailInfo.order && this.state.detailInfo.order.order_no) {
                return(
                    <View style={style.pageRight}>
                        <View style={style.orderNoBox}>
                            <Text style={style.bigText}>
                                订单号：{this.state.detailInfo.order.order_no}
                            </Text>
                            <Text style={style.bigText}>
                                时间：{this.state.detailInfo.order.submit_time}
                            </Text>
                        </View>
                        <View style={style.orderInfo}>
                            <ScrollView>
                                <View style={style.userInfo}>
                                    <Text style={{flex: 1}}>

                                        会员：<Text style={{color: '#4B8AF2'}}>{this.state.detailInfo.user.nick_name} {this.state.detailInfo.user.mobile}</Text>
                                    </Text>
                                    <Text style={{flex: 1}}>
                                        {/*导购：{this.state.detailInfo.shopOrder.clerk.name}*/}
                                    </Text>
                                    <TouchableWithoutFeedback>
                                        <View style={style.noteBox}>
                                            <CXIcon name='beizhu' color='#909090' size={20}></CXIcon>
                                            <Text style={{marginLeft: 10}} numberOfLines={1}>备注: {this.state.detailInfo.order.note || ''}</Text>
                                        </View>
                                    </TouchableWithoutFeedback>
                                </View>
                                <View style={style.orderDetailInfo}>
                                    <View style={[style.detailInfoItem, style.detailInfoItemTitle]}>
                                        <View style={{flex: 3}}>
                                            <Text style={style.mText}>
                                                商品名称
                                            </Text>
                                        </View>
                                        <View style={style.detailCenter}>
                                            <Text style={style.mText}>
                                                数量
                                            </Text>
                                        </View>
                                        <View style={style.detailCenter}>
                                            <Text style={style.mText}>
                                                单价
                                            </Text>
                                        </View>
                                        <View style={style.detailCenter}>
                                            <Text style={style.mText}>
                                                小计
                                            </Text>
                                        </View>
                                        <View style={style.detailCenter}>
                                            <Text style={style.mText}>
                                                售后
                                            </Text>
                                        </View>
                                    </View>
                                    <FlatList
                                        keyExtractor={(item, index) => index.toString()}
                                        data={this.state.detailInfo.order.items}
                                        renderItem={({item,index}) => this._renderGoodsList(item,index)}
                                        extraData={this.state}
                                    >
                                    </FlatList>
                                </View>
                                <View style={style.orderMoneyInfo}>
                                    <Text style={{flex: 1, fontWeight: 'bold'}}>
                                        共{this.state.detailInfo.order.count}件
                                    </Text>
                                    <Text style={{fontWeight: 'bold'}}>
                                        商品总额：￥{(this.state.detailInfo.order.items_total_yuan - this.state.detailInfo.adjustments.order_discount_amount).toFixed(2)}
                                    </Text>
                                    <Text style={{fontWeight: 'bold',paddingLeft: 10}}>
                                        实收金额：<Text style={{color: mainBackgroundColor}}>￥{fen_to_yuan(this.state.detailInfo.paymentDetail.actual)}</Text>
                                    </Text>
                                    <Text style={{fontWeight: 'bold',paddingLeft: 10}}>
                                        应付金额：￥{this.state.detailInfo.order.total_yuan}
                                    </Text>
                                    <Text style={{fontWeight: 'bold',paddingLeft: 10}}>
                                        抹零金额：￥{fen_to_yuan(this.state.detailInfo.paymentDetail.wipe)}
                                    </Text>
                                    <Text style={{fontWeight: 'bold',paddingLeft: 10}}>
                                        找零金额：￥{fen_to_yuan(this.state.detailInfo.paymentDetail.remaining)}
                                    </Text>
                                </View>
                                <View style={style.orderMoneyInfo}>
                                    <Text style={{flex: 1}}>
                                        优惠信息：
                                    </Text>
                                    <Text>
                                        积分：{this.state.detailInfo.adjustments.point_amount || 0}
                                    </Text>
                                    <Text style={{width: 200, textAlign: 'right'}}>
                                        优惠券：{this.state.detailInfo.adjustments.coupon_amount || 0}
                                    </Text>
                                </View>
                                <View style={[style.orderMoneyInfo, {borderBottomWidth: 0}]}>
                                    <Text style={{flex: 1}}>
                                        支付详情：
                                    </Text>
                                    {this._renderPayments(this.state.detailInfo.payments)}
                                </View>
                            </ScrollView>
                        </View>
                        <View style={style.bottomBox}>
                            <Text style={style.btnText} onPress={() => this._submitAfterSale()}>
                                申请售后
                            </Text>
                            <Text style={style.print} onPress={() => this.printOrder()}>
                                打印
                            </Text>
                    </View>
                    </View>
                )
            }
        } else {
            return(
                <View>

                </View>
            )
        }
    }
    //点击搜索
    _clickSearchOrder(){
        let {storeAction} = this.props;
        storeAction.getOrderList(1,this.props.user_id,this.state.searchVal,(res) =>{
            if (res && res.status && res.data && res.data.length){
                let firstOrderNo = res.data[0].order_no;
                storeAction.getOrderDetail(firstOrderNo, (res) => {
                    if (res && res.status && res.data) {

                        this.setState({
                            detailInfo: res.data,
                            order_no: firstOrderNo
                        })
                    }
                });
            }
        });

    }
    //点击订单变色
    _clickOrderItem(index,order_no){
        this.setState({
            activeIndex:index
        });
        this.setState({
            order_no: order_no
        });
        let {storeAction} = this.props;
        storeAction.getOrderDetail(order_no, (res) => {
            console.log(res);
            if (res && res.status && res.data) {

                console.log('获取到的数据', res.data);
                this.setState({
                    detailInfo: res.data
                })
            }
        });
    }
    // 多选框
    checkBoxChange(index) {
        let detailInfo = this.state.detailInfo;
        let item = detailInfo.order.items[index];
        if (item.is_refunded) return
        item.isChecked = !item.isChecked;
        this.setState({
            detailInfo: detailInfo
        })
    }

    //渲染支付方式
    _renderPayments(payments){
        return payments.map((item,index) =>{
            return (
                <Text style={[index == payments.length -1 ? style.paymentsLast : '']} key={index}>
                    {item.channel_text}支付：￥{item.amount_yuan}
                </Text>
            )
        })
    }
    render() {
        let{storeState} = this.props;
        return (
            <View style={style.page}>
                <StatusBar hidden={true} />

                <View style={style.box}>
                    <View style={style.pageLeft}>

                        <View style={style.searchBox}>
                            <TextInput
                                style={style.searchInput}
                                placeholder={"请输入订单号搜索"}
                                onChangeText={(searchVal) =>this.setState({searchVal})}
                            />
                            <Text style={style.searchText} onPress={()=>{this._clickSearchOrder()}}>搜索</Text>
                        </View>
                        <View style={style.orderList}>
                            <View>
                                <FlatList
                                    style={{height: 500}}
                                    keyExtractor={(item, index) => index.toString()}
                                    data={storeState.orderList}
                                    renderItem={({item,index}) => this._renderOrderList(item,index)}
                                    onEndReached = {()=> this._onLoadMore()}
                                    onEndReachedThreshold={0.1}
                                    extraData={storeState.orderList}
                                    ListEmptyComponent={this._createEmptyView}
                                >
                                </FlatList>

                            </View>
                        </View>
                    </View>
                    {this._renderOrderDetail()}

                </View>

            </View>
        )
    }
};

const style = StyleSheet.create({
    page: {
        height: '100%',
        backgroundColor: '#fff',
    },
    box: {
        flexDirection: 'row',
        height: '100%',
        // marginTop: 60
    },
    paymentsLast:{
        width: 200,
        textAlign: 'right'
    },
    pageLeft: {
        width: 430
    },
    searchBox: {
        flexDirection: 'row',
        height: 80,
        alignItems: 'center',
        borderBottomWidth: 1,
        borderColor: '#DBDBDB',
        paddingHorizontal: 15
    },
    searchInput: {
        paddingLeft: 20,
        flex: 1,
        height: 50,
        backgroundColor: '#F3F3F3',
    },
    searchText: {
        width: 80,
        backgroundColor: mainBackgroundColor,
        textAlign: 'center',
        lineHeight: 50,
        color: white,
    },
    orderList: {
        flex: 1
        // height: '100%',
    },
    orderItem: {
        padding: 15,
        borderBottomWidth: 1,
        borderColor: '#DBDBDB'
    },
    orderItemActive: {
        backgroundColor: '#4B8AF2'
    },
    orderItemActiveText: {
        color: white
    },
    sItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginVertical: 2
    },
    itemMoney: {
        color: '#4B8AF2',
        fontSize: 20
    },
    mText: {
        color: '#909090',
        fontSize: 12
    },
    pageRight: {
        height: '100%',
        flex: 1,
        backgroundColor: '#F3F3F3',
        borderLeftWidth: 1,
        borderColor: '#DBDBDB'
    },
    orderNoBox: {
        flexDirection: 'row',
        height: 80,
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottomWidth: 1,
        borderColor: '#DBDBDB',
        paddingHorizontal: 30
    },
    bigText: {
        fontSize: 18,
        color: '#4A4A4A'
    },
    orderInfo: {
        padding: 30,
        paddingBottom: 80,
        flex: 1
    },
    userInfo: {
        flexDirection: 'row'
    },
    noteBox: {
        width: 220,
        flexDirection: 'row'
    },
    orderDetailInfo: {
        marginTop: 30,
        backgroundColor: white,
        borderWidth: 1,
        borderColor: '#D7D7D7',
        borderRadius: 4,
        paddingBottom: 80
    },
    detailInfoItem: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 20,
        borderBottomWidth: 1,
        borderColor: '#D7D7D7',
    },
    detailCenter: {
      flex: 1,
      alignItems: 'center'
    },
    detailInfoItemTitle: {
        paddingVertical: 10
    },
    detailBtn: {
        padding: 15,
        borderWidth: 1,
        borderColor: mainBackgroundColor,
        borderRadius: 4,
        color: mainBackgroundColor
    },
    orderMoneyInfo: {
        paddingVertical: 30,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderColor: '#D7D7D7',
    },
    bottomBox: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: white,
        height: 80,
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 30,
        justifyContent: 'flex-end'
    },
    btnText: {
        color: mainBackgroundColor,
        paddingVertical: 10,
       textAlign: 'center',
        width: 120,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: mainBackgroundColor,
        marginRight: 40
    },
    print: {
        color: white,
        paddingVertical: 10,
        textAlign: 'center',
        width: 120,
        borderRadius: 4,
        backgroundColor: mainBackgroundColor
    }
});

export default connect(state =>({
    storeState: state.store
}),dispatch =>({
    storeAction: bindActionCreators(storeActions,dispatch)
}))(orderPage);